export class Vector2D {
    constructor(public x: number, public y: number) {}

    public add(other: Vector2D): Vector2D {
        return new Vector2D(this.x + other.x, this.y + other.y);
    }

    public subtract(other: Vector2D): Vector2D {
        return new Vector2D(this.x - other.x, this.y - other.y);
    }

    public multiply(scalar: number): Vector2D {
        return new Vector2D(this.x * scalar, this.y * scalar);
    }

    public divide(scalar: number): Vector2D {
        if (scalar === 0) throw new Error('除数不能为零');
        return new Vector2D(this.x / scalar, this.y / scalar);
    }

    public magnitude(): number {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    }

    public normalize(): Vector2D {
        const mag = this.magnitude();
        if (mag === 0) return new Vector2D(0, 0);
        return this.divide(mag);
    }

    public dot(other: Vector2D): number {
        return this.x * other.x + this.y * other.y;
    }

    public distance(other: Vector2D): number {
        return this.subtract(other).magnitude();
    }

    public angle(): number {
        return Math.atan2(this.y, this.x);
    }

    public rotate(angle: number): Vector2D {
        const cos = Math.cos(angle);
        const sin = Math.sin(angle);
        return new Vector2D(
            this.x * cos - this.y * sin,
            this.x * sin + this.y * cos
        );
    }

    public lerp(other: Vector2D, t: number): Vector2D {
        return new Vector2D(
            this.x + (other.x - this.x) * t,
            this.y + (other.y - this.y) * t
        );
    }

    public clone(): Vector2D {
        return new Vector2D(this.x, this.y);
    }

    public equals(other: Vector2D): boolean {
        return this.x === other.x && this.y === other.y;
    }

    public toString(): string {
        return `Vector2D(${this.x}, ${this.y})`;
    }
}